package com.pro01.backend.tracker;

import com.turn.ttorrent.tracker.Tracker;
import com.turn.ttorrent.tracker.TrackedTorrent;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FilenameFilter;
import java.net.InetAddress;
import java.net.InetSocketAddress;

@Component
public class TrackerManager {

    private Tracker tracker;

    @PostConstruct
    public void start() {
        try {
            //InetAddress ip = InetAddress.getLocalHost();
            //tracker = new Tracker(new InetSocketAddress(ip, 6969));

            tracker = new Tracker(new InetSocketAddress("0.0.0.0", 6969));
            InetAddress ip = InetAddress.getLocalHost(); // 仅用于打印
            System.out.println("Tracker 启动成功: http://" + ip.getHostAddress() + ":6969/announce");


            // 加载已有种子
            File torrentDir = new File(System.getProperty("user.dir"), "uploads/torrents");
            File[] files = torrentDir.listFiles((dir, name) -> name.endsWith(".torrent"));
            if (files != null) {
                for (File f : files) {
                    tracker.announce(TrackedTorrent.load(f));
                    System.out.println("已加载种子: " + f.getName());
                }
            }

            // 启动 tracker 服务
            tracker.start();
            System.out.println("Tracker 启动成功: http://" + ip.getHostAddress() + ":6969/announce");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void registerTorrent(File torrentFile) {
        try {
            tracker.announce(TrackedTorrent.load(torrentFile));
            System.out.println("新种子注册成功: " + torrentFile.getName());
        } catch (Exception e) {
            System.err.println("注册新种子失败: " + torrentFile.getName());
            e.printStackTrace();
        }
    }

    @PreDestroy
    public void stop() {
        if (tracker != null) {
            tracker.stop();
            System.out.println("Tracker 已停止");
        }
    }

}
